import { HttpException, HttpStatus, Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { MoreThan, Repository } from 'typeorm'
import { BaseService } from '@/common/base/base.service'
import { WheelPrize } from './entities/wheel-prize.entity'

@Injectable()
export class WheelPrizeService extends BaseService<WheelPrize, 'wheelPrizeId'> {
  constructor(
    @InjectRepository(WheelPrize)
    repo: Repository<WheelPrize>,
  ) {
    super(repo)
  }

  // 权重轮盘法
  async draw() {
    const prizeList = await this.findAll({
      where: { isEnabled: true, remaining: MoreThan(0), probability: MoreThan(0), isDeleted: false },
    })
    console.log('[ prizeList ] >', prizeList)

    if (!prizeList.length) {
      throw new HttpException('没有可抽的奖品', HttpStatus.BAD_REQUEST)
    }

    const totalWeight = prizeList.reduce((sum, p) => sum + p.probability, 0)
    const randomValue = Math.random() * totalWeight

    let current = 0
    let selected = prizeList[0]

    for (const prize of prizeList) {
      current += prize.probability
      if (randomValue <= current) {
        selected = prize
        break
      }
    }

    selected.remaining -= 1
    await this.save(selected)
    return selected
  }
}
